package com.sh.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.baoyz.widget.PullRefreshLayout;
import com.sh.Application.BaseApplication;
import com.sh.adapter.MainProductWaterFallAdapter;
import com.sh.secondhand.PoductForGenreActivity;
import com.sh.secondhand.ProductDetailActivity;
import com.sh.secondhand.ProductGenreChoiseActivity;
import com.sh.secondhand.R;
import com.sh.struts.LoginInfo;
import com.sh.struts.ProductData;
import com.sh.utils.BackgroundManagerUtils;
import com.sh.utils.CommonStringUtils;

import java.util.*;

public class MainProductViewFrament extends Fragment {
    private static final String TAG = "MainProductFrament";
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    @BindView(R.id.product_show)
    RecyclerView productView;

    protected List<Integer> loadedProductIds;
    private StaggeredGridLayoutManager mLayoutManager;
    private MainProductWaterFallAdapter mAdapter;
    private boolean canload = true; // 作为是否还有数据的标志
    private View rootView;
    private PullRefreshLayout refreshLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.products_fragment, container,false);
            ButterKnife.bind(this,rootView);
            initRecylerView();
        }
        return rootView;
    }

    public MainProductViewFrament(){}

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static MainProductViewFrament newInstance(int sectionNumber, PullRefreshLayout pullRefreshLayout) {
        MainProductViewFrament fragment = new MainProductViewFrament();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setRefreshLayout(pullRefreshLayout);
        fragment.setArguments(args);
        return fragment;
    }


    public void initRecylerView(){
        productView.setNestedScrollingEnabled(false);
        mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mAdapter = new MainProductWaterFallAdapter(BaseApplication.getInstance(), new ArrayList<>());
        productView.setLayoutManager(mLayoutManager);
        productView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(position -> {
            Intent webView = new Intent(this.getActivity(), ProductDetailActivity.class);
            webView.putExtra("product_data",mAdapter.getItemByPosition(position-1));
            startActivity(webView);
        });
        mAdapter.setHeadClickListener((view,genre) -> {
            if(!"all".equals(genre)) {
                Intent productGenreView = new Intent(getActivity(), PoductForGenreActivity.class);
                productGenreView.putExtra("genre", genre);
                startActivity(productGenreView);
            }else{
                Intent intent = new Intent(getActivity(), ProductGenreChoiseActivity.class);
                intent.putExtra("redirect", true);
                startActivity(intent);
            }
        });
        productView.addOnScrollListener(new ScrollListener() {
            @Override
            public void onLoadMore() {
                if (canload) {
                    mAdapter.setLoadState(mAdapter.LOADING);
                    new ProductInfo(loadedProductIds, 10).execute((Void) null);
                    mAdapter.setLoadState(mAdapter.LOADING_COMPLETE);
                } else {
                    mAdapter.setLoadState(mAdapter.LOADING_END);
                }
            }
        });
        loadedProductIds = new ArrayList<>();
        new ProductInfo(loadedProductIds, 10).execute((Void) null);
    }

    abstract class ScrollListener extends RecyclerView.OnScrollListener {
        // 用来标记是否正在向上滑动
        private boolean isSlidingUpward = false;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
            // 当不滑动时
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                // 获取最后一个完全显示的itemPosition
                if (!canScrollDown(recyclerView) && isSlidingUpward) {
                    // 加载更多
                    onLoadMore();
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            int topRowVerticalPosition =
                    (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
            refreshLayout.setEnabled(topRowVerticalPosition >= 0);
            // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
            isSlidingUpward = dy > 0;
            if (!canScrollDown(recyclerView) && isSlidingUpward) {
                // 加载更多
                onLoadMore();
            }
        }

        /**
         * 加载更多回调
         */
        public abstract void onLoadMore();
    }

    private boolean canScrollDown(RecyclerView recyclerView) {
        return ViewCompat.canScrollVertically(recyclerView, 1);
    }

    public class ProductInfo extends AsyncTask<Void, Void, Void> {
        List<Integer> productIds;
        Integer count;

        public ProductInfo(List<Integer> productIds, Integer count) {
            this.productIds = productIds;
            this.count = count;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            LoginInfo loginInfo = BaseApplication.getLoginInfo();
            Integer userId = loginInfo == null ? 0 : loginInfo.getUserId();
            List<Map<String, String>> products = BackgroundManagerUtils.getProducts(CommonStringUtils.join(productIds, ","), count, null,null);
            Set<Integer> productIdSet = new HashSet<>(loadedProductIds);
            if (products.size() < count) {
                canload = false;
            }
            List<ProductData> datas = new ArrayList<>();
            for (Map map : products) {
                if (productIdSet.add(CommonStringUtils.safeInteger(map.get("pro_id")))) {
                    ProductData productData = new ProductData(map);
                    datas.add(productData);
                }
            }
            getActivity().runOnUiThread(() -> {
                mAdapter.addItems(datas);
                if(!canload){
                    mAdapter.setLoadState(mAdapter.LOADING_END);
                    mAdapter.notifyDataSetChanged();
                }
            });
            loadedProductIds = new ArrayList<>(productIdSet);
            return null;
        }
    }

    public class RefreshInfo extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            LoginInfo loginInfo = BaseApplication.getLoginInfo();
            Integer userId = loginInfo == null ? 0 : loginInfo.getUserId();
            List<Map<String, String>> products = BackgroundManagerUtils.refreshProducts(userId);
            Set<Integer> productIdSet = new HashSet<>(loadedProductIds);
            List<ProductData> datas = new ArrayList<>();
            for (Map map : products) {
                if (productIdSet.add(CommonStringUtils.safeInteger(map.get("pro_id")))) {
                    ProductData productData = new ProductData(map);
                    datas.add(productData);
                }
            }
            getActivity().runOnUiThread(() -> {
                mAdapter.insertDatas(datas,0);
            });
            loadedProductIds = new ArrayList<>(productIdSet);
            return null;
        }
    }
    public void refreshView(){
        mAdapter.setLoadState(mAdapter.LOADING);
        new RefreshInfo().execute((Void)null);
        if(!canload) {
            mAdapter.setLoadState(mAdapter.LOADING_END);
            mAdapter.notifyDataSetChanged();
        }else{
            mAdapter.setLoadState(mAdapter.LOADING_COMPLETE);
        }
    }

    /**
     * 在子线程里需要使用Toast
     *
     * @param context
     * @param message
     */
    public void showToastOnThread(Context context, String message) {
        getActivity().runOnUiThread(() -> Toast.makeText(context, message, Toast.LENGTH_SHORT).show());
    }

    public void setRefreshLayout(PullRefreshLayout refreshLayout){
        this.refreshLayout = refreshLayout;
    }
}
